package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-data-hub/cache"
	"novel-data-hub/models"
	"strconv"
	"time"
)

func WareHouseManageList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	/*
		SELECT
		  ware_house_manages.id as ManageId,
		  ware_houses.ware_code as WareCode,
		  ware_houses.ware_name as WareName,
		  ware_houses.ware_type as WareType,
		  ware_house_manages.manage_code as ManageCode,
		  ware_house_manages.manage_place as ManagePlace,
		  ware_house_manages.manage_name as ManageName
		FROM
		  ware_houses
		  LEFT JOIN ware_house_manages ON ware_house_manages.wid = ware_houses.id
		WHERE
		  ware_house_manages.id = 1
	*/
	var list []models.WareHouseManageList
	redis_key := "ware_house_manage_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("ware_houses").
			Select("ware_house_manages.id as ManageId",
				"ware_houses.ware_code as WareCode",
				"ware_houses.ware_name as WareName",
				"ware_houses.ware_type as WareType",
				"ware_house_manages.manage_code as ManageCode",
				"ware_house_manages.manage_place as ManagePlace",
				"ware_house_manages.manage_name as ManageName",
			).
			Joins("LEFT JOIN ware_house_manages ON ware_house_manages.wid = ware_houses.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	models.DB.Model(&models.WareHouseManage{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  list,
		"count": count,
	})
	return
}

func WareHouseManageDetail(c *gin.Context) {
	id := c.Query("id")

	var list models.WareHouseManageList
	redis_key := "ware_house_manage_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("ware_houses").
			Select("ware_house_manages.id as ManageId",
				"ware_houses.ware_code as WareCode",
				"ware_houses.ware_name as WareName",
				"ware_houses.ware_type as WareType",
				"ware_house_manages.manage_code as ManageCode",
				"ware_house_manages.manage_place as ManagePlace",
				"ware_house_manages.manage_name as ManageName",
			).
			Joins("LEFT JOIN ware_house_manages ON ware_house_manages.wid = ware_houses.id").
			Where("ware_house_manages.id = ?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
	return
}
